package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IRoleService roleService;

    // /employee/list
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") EmployeeQueryObject qo) {
        PageInfo<Employee> pageInfo = employeeService.query(qo);
        model.addAttribute("pageInfo", pageInfo);

        //查询所有部门数据，存在模型中
        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments", departments);

        return "employee/list"; // /templates/employee/list.ftl
    }

    @RequestMapping("/input")
    public String input(Model model, Long id) {
        //查询所有部门数据，存在模型中
        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments", departments);

        List<Role> roles = roleService.listAll();
        model.addAttribute("roles", roles);

        if (id != null) {
            Employee employee = employeeService.select(id);
            model.addAttribute("employee", employee);
        }
        return "employee/input";
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult insertOrUpdate(Employee employee, Long[] ids) {
        try {
            if (employee.getId() != null) {
                employeeService.update(employee, ids);
            } else {
                employeeService.insert(employee, ids);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"操作失败");
        }
    }

    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
            employeeService.delete(id);
        }
        return "redirect:/employee/list.do";
    }

    @RequestMapping("/batchDelete")
    @ResponseBody
    public JsonResult batchDelete(Long[] ids){
        try {
            employeeService.batchDelete(ids);
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"删除失败");
        }
    }

    @RequestMapping("/updatePWD")
    public String updatePWD(){
        return "employee/updatePwd";
    }

    @RequestMapping("/updatePwd")
    @ResponseBody
    public JsonResult updatePwd(String oldPassword, String newPassword){
        Subject subject = SecurityUtils.getSubject();
        Employee employee = (Employee) subject.getPrincipal();
        System.out.println(employee);
        boolean flag = employeeService.updatePwd(employee, oldPassword, newPassword);
        if (flag) {
            subject.logout();
        }
        return new JsonResult();
//        return "redirect:/login.html";
    }

    @RequestMapping("/resetPWD")
    public String resetPWD(Model model, Long id) {
        Employee employee = employeeService.select(id);
        model.addAttribute("employee", employee);
        return "employee/resetPwd";
    }

    @RequestMapping("/resetPwd")
    @ResponseBody
    public JsonResult resetPwd(Long id, String newPassword) {
        if (newPassword != null) {
            employeeService.resetPwd(id, newPassword);
        }
        return new JsonResult();
    }

    @RequestMapping("/checkName")
    @ResponseBody
    public HashMap checkName(String name, Long id){
        HashMap<Object, Object> map = new HashMap<>();
        Employee employee = employeeService.select(id);
        if (id != null) {
            if (employee.getName().equals(name)) {
                map.put("valid", true);
                return map;
            } else {
                Employee employee2 = employeeService.selectByName(name);
                map.put("valid", employee2 == null);
                return map;
            }
        } else {
            Employee employee3 = employeeService.selectByName(name);
            map.put("valid", employee3 == null);
            return map;
        }
    }

    @RequestMapping("/resetStatus")
    @ResponseBody
    public JsonResult resetStatus(Long id){
        Employee employee = employeeService.select(id);
        if (employee.isStatus()) {
            employee.setStatus(false);
            employeeService.resetStatus(employee);
        } else {
            employee.setStatus(true);
            employeeService.resetStatus(employee);
        }
        return new JsonResult();
    }

    /**
     * 导出
     */
    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws IOException {
        //文件下载的响应头（让浏览器访问资源的的时候以下载的方式打开）
        response.setHeader("Content-Disposition","attachment;filename=employee.xls");
        //调用service的导出方法
        Workbook workbook = employeeService.exportXls();
        //输出文件
        workbook.write(response.getOutputStream());
    }

    /**
     * 导入
     */
    @RequestMapping("/importXls")
    @ResponseBody
    public JsonResult importXls(MultipartFile file) throws IOException {
        System.out.println(file.getOriginalFilename());
        //读取上传过来的文件
        employeeService.importXls(file);
        return new JsonResult();
    }
}
